﻿
var common = {

    commonAjax: function (options) {

        common.loading(options.loadingCtrl);

        $.ajax({
            type: options.type,
            //contentType: 'application/json',
            url: options.url,
            data: options.data,
            //dataType: 'json',
            success: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                if (common.checkValue(options.alert)) {
                    swal({
                        title: "",
                        text: "提交成功, 2秒后自动关闭",
                        type: "success",
                        timer: 2000,
                        showConfirmButton: true
                    },
                    function () {
                        swal.close();
                        if (common.checkValue(options.sMethod))
                            options.sMethod(ctx);
                    });

                    return;
                }

                if (common.checkValue(options.sMethod))
                    options.sMethod(ctx, options.args);
            },
            error: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                var values = {};
                values.url = options.url;
                values.data = JSON.stringify(options.data);
                values.message = ctx.responseText;
                values.status = ctx.status;
                values.statusText = ctx.statusText;

                common.commonAjax({ type: 'Post', url: '/api/Util/LogError', data: values });

                if (options.fMethod === undefined || options.fMethod === null || options.fMethod === "") {

                    if (common.checkValue(ctx.responseJSON) && common.checkValue(ctx.responseJSON.Message) && ctx.responseJSON.Message == "请登录") {
                        common.alertMessage("", ctx.status);
                    }
                    else if (common.checkValue(ctx.responseJSON) && common.checkValue(ctx.responseJSON.Message))
                        common.alertMessage(ctx.responseJSON.Message, ctx.status);
                    else
                        common.alertMessage("操作失败,请重新提交", ctx.status);

                    return;
                }

                options.fMethod(ctx);
            }
        });
    },

    getUrlArgStr: function () {

        var url = location.search;
        var param = [];
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                param[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }

        return param;
    },

    ListBaseData: function (ctx, args) {
        if (ctx === "" || ctx === null) {
            common.alertMessage("基础数据错误");
            return;
        }
        lstAmout = ctx.ResponseList;
        Enumerable.From(lstAmout).ForEach(function (obj) {
            $("#" + args).append("<option value='" + obj.RuleNO + "'>" + obj.Description + "</option>");
        });
    },

    alertMessage: function (msg, status) {

        if (status === undefined)
            status = 0;

        switch (status) {

            case 400:
                if (common.checkValue(msg))
                    swal({
                        text: msg,
                        title: '',
                        type: "warning",
                        html: true
                    });
                else
                    window.location = "/login.html";
                break;
            case 401:
                window.location = "/login.html";
                break;
            case 500:
                swal({
                    text: "出现错误，请联系管理员或稍后重试",
                    title: '',
                    type: "warning",
                    html: true
                });
                break;
            default:
                swal({
                    //text: "操作失败,请重新提交。",
                    text: msg,
                    title: '',
                    type: "warning",
                    html: true
                });
        }
    },

    showMessage: function (msg, fn) {
        swal({
            title: "",
            text: msg,
            type: "warning",
            timer: 2000,
            showConfirmButton: true
        },
        function () {
            swal.close();
            if (common.checkValue(fn))
                fn();
        });

    },

    loading: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            //loadingCtrl.append('<div class="message-loading-overlay"><img class="icon-spinner icon-spin" style="width: 212px"></img></div>')
            loadingCtrl.append('<div class="message-loading-overlay"><div class="loding-img" style="width: 212px"></div></div>');
        }
    },

    loadComplete: function (loadingCtrl) {
        if (common.checkValue(loadingCtrl)) {
            loadingCtrl.find('.message-loading-overlay').remove();
        }
    },

    GetSHA: function (val) {

        var shaObj = new jsSHA("SHA-512", "TEXT");
        shaObj.update(val);
        return shaObj.getHash("HEX");
    },

    encrypt: function (str, pwd) {
        if (pwd === null || pwd.length <= 0) {
            pwd = "bingo123";
        }

        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.ceil(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        if (mult < 2) {
            alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
            return null;
        }
        var salt = Math.round(Math.random() * 1000000000) % 100000000;
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i++) {
            enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
            if (enc_chr < 16) {
                enc_str += "0" + enc_chr.toString(16);
            } else enc_str += enc_chr.toString(16);
            prand = (mult * prand + incr) % modu;
        }
        salt = salt.toString(16);
        while (salt.length < 8) salt = "0" + salt;
        enc_str += salt;

        return enc_str;
    },

    decrypt: function (str, pwd) {
        if (str == null || str.length < 8) {
            alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
            return;
        }
        if (pwd == null || pwd.length <= 0) {
            pwd = "bingo123";
        }
        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.round(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        var salt = parseInt(str.substring(str.length - 8, str.length), 16);
        str = str.substring(0, str.length - 8);
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i += 2) {
            enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
            enc_str += String.fromCharCode(enc_chr);
            prand = (mult * prand + incr) % modu;
        }
        return enc_str;
    },

    GetCtrlValues: function (option) {
        var contentID = option.ContentID.toString().indexOf("#") > 0 ? option.ContentID : "#" + option.ContentID;
        var objParent = $(contentID);

        var resultData = {};
        objParent.find("input[type='text'],textarea,input[type='hidden'],input[type='tel'],input[type='email']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        });

        objParent.find("input[type='password']").each(function () {
            var objThis = $(this);
            var objVal = objThis.val();
            if (objVal !== undefined || objVal !== "")
                objVal = common.GetSHA(objVal);
            resultData[objThis.attr("id")] = objVal;
        });
        objParent.find("input[type='number']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        });
        objParent.find("select").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        });
        objParent.find("input[type='radio']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked"))
                resultData[objThis.attr("name")] = objThis.val();
        });
        objParent.find("input[type='checkbox']").each(function () {
            var objThis = $(this);
            if ($(this).attr("checked") || $(this).prop("checked")) {
                var TempArr = resultData[objThis.attr("name")];
                if (TempArr === undefined)
                    TempArr = "";

                TempArr += objThis.val() + "$%#";
                resultData[objThis.attr("name")] = TempArr;
            }
        });
        objParent.find("input[type='date']").each(function () {
            var objThis = $(this);
            resultData[objThis.attr("id")] = objThis.val();
        });
        objParent.find("a").each(function () {
            var objThis = $(this);
            if ($(this).attr("class") == "chosen" || $(this).prop("class") == "chosen")
                resultData[objThis.attr("name")] = objThis.attr("value");
        });
        if (option.returnJson === undefined || !option.returnJson)
            return resultData;
        else
            return JSON.stringify(resultData);

    },

    CacheObj: function (data, name) {

        var cacheArray = store.get(name);
        if (!common.checkValue(cacheArray))
            cacheArray = new Array();

        var obj = {};

        switch (name) {
            case "Project":
                var result = data.ResponseDict;
                obj.ProjectID = result.ProjectID;
                obj.ProjectName = result.ProjectName;
                obj.Address = result.Address;
                obj.CreateDate = result.CreateDate;
                obj.Amount = result.Amount;
                obj.StartDate = result.StartDate;
                obj.EndDate = result.EndDate;
                obj.Cover = result.Cover;
                obj.CreatorBelongID = result.CreatorBelongID;
                obj.CreatorType = result.CreatorType;
                obj.CreatorName = result.CreatorName;
                obj.PastDays = result.PastDays;
                obj.Favorites = result.Favorites;
                break;
        }

        for (var i = 0; i < cacheArray.length; i++) {
            if (obj.ProjectID == cacheArray[i].ProjectID)
                return;
        }

        if (cacheArray.length < 5) {
            cacheArray.push(obj);
        }
        else {
            cacheArray.splice(0, 1);
            cacheArray.push(obj);
        }

        store.set(name, cacheArray);

    },

    ListCacheObj: function (objName) {
        var cacheArray = store.get(objName);
        if (!common.checkValue(cacheArray) || cacheArray.length === 0)
            return;
        return cacheArray.reverse();
    },

    CreateController: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', []);

        if (option.htmlFilter) {
            app.filter('to_trusted', ['$sce', function ($sce) {
                return function (text) {
                    return $sce.trustAsHtml(text);
                };
            }]);
        }

        app.controller(option.name, function ($http, $scope) {
            if (!common.checkValue(option.url)) {
                $scope.update = function (data) {

                    $scope.names = data;
                    $scope.$apply();
                }
            }
            else {
                $http.get(option.url).success(function (data) {

                    switch (option.objType) {
                        case "object":
                            $scope.names = data.ResponseObj;
                            break;
                        case "list":
                            $scope.names = data.ResponseList;
                            break;
                        case "dict":
                            $scope.names = data.ResponseDict;
                            break;
                        case "string":
                            $scope.names = data.ResponseStr;
                            break;
                        case "json":
                            $scope.names = data.ResponseJson.data;
                            break;
                    }

                    if (common.checkValue(option.cacheName))
                        common.CacheObj(data, option.cacheName);

                    if (common.checkValue(option.sMethod))
                        option.sMethod(data);

                }).error(function (data, status, headers, config) {
                    common.alertMessage(data.Message, status);
                });
            }
        });
    },

    CreateService: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', ['ngRoute']);

        if (option.htmlFilter) {
            app.filter('to_trusted', ['$sce', function ($sce) {
                return function (text) {
                    return $sce.trustAsHtml(text);
                };
            }]);
        }

        app.factory('accountService', function ($http, $q) {
            return {
                getData: function () {
                    var d = $q.defer();

                    if (!common.checkValue(option.url)) {
                        $scope.update = function (data) {

                            $scope.names = data;
                            $scope.$apply();
                        }
                    }
                    else {
                        $http.get(option.url).then(function (response) {
                            switch (option.objType) {
                                case "object":
                                    d.resolve(data.ResponseObj);
                                    break;
                                case "list":
                                    d.resolve(data.ResponseList);
                                    break;
                                case "dict":
                                    d.resolve(data.ResponseDict);
                                    break;
                                case "string":
                                    d.resolve(data.ResponseStr);
                                    break;
                                case "json":
                                    d.resolve(data.ResponseJson.data);
                                    break;
                            }
                        }, function err(reason) {
                            d.reject(reason);
                        });
                        return d.promise;
                    }
                }
            }
        })

        app.config(function ($routeProvider) {
            $routeProvider
            .when(option.url, {
                controller: option.name,
                //templateUrl: 'views/account.html',
                resolve: {
                    // We specify a promise to be resolved
                    names: function (accountService) {
                        return accountService.getData()
                    }
                }
            })
        })

        app.controller(option.name, function ($http, $scope) {
            if (!common.checkValue(option.url)) {
                $scope.update = function (data) {

                    $scope.names = data;
                    $scope.$apply();
                }
            }
            else {
                $http.get(option.url).success(function (data) {

                    switch (option.objType) {
                        case "object":
                            $scope.names = data.ResponseObj;
                            break;
                        case "list":
                            $scope.names = data.ResponseList;
                            break;
                        case "dict":
                            $scope.names = data.ResponseDict;
                            break;
                        case "string":
                            $scope.names = data.ResponseStr;
                            break;
                        case "json":
                            $scope.names = data.ResponseJson.data;
                            break;
                    }

                    if (common.checkValue(option.cacheName))
                        common.CacheObj(data, option.cacheName);

                    if (common.checkValue(option.sMethod))
                        option.sMethod(data);

                }).error(function (data, status, headers, config) {
                    common.alertMessage(data.Message, status);
                });
            }
        });
    },

    CreatePagingCtrl: function (option) {

        var app = common.checkValue(option.app) ? option.app : angular.module('myApp', ['ng-pagination']);
        var limit = 10;

        if (common.checkValue(option.limit))
            limit = option.limit;

        if (!common.checkValue(option.pars)) {
            option.pars = {};
        }

        option.pars.Start = 1;
        option.pars.Limit = limit;

        app.controller(option.name, function ($http, $scope) {

            if (!common.checkValue(option.url)) {

                $scope.update = function (data) {

                    var result;
                    var count;
                    if (!common.checkValue(option.objType)) {
                        result = data.ResponseList;
                        count = data.Count;
                    }
                    else if (option.objType == "json") {
                        result = data.ResponseJson.data;
                        count = data.ResponseJson.count;
                    }

                    $scope.names = result;
                    $scope.count = count;

                    var total = Math.floor(count / limit);

                    if (count % limit > 0)
                        total++;

                    $scope.pageCount = total;

                    $scope.$apply();
                }

                $scope.onPageChange = function () {
                    option.pageChanged($scope);
                };
            }
            else {
                $http.post(option.url, option.pars).success(function (data) {

                    var result;
                    var count;
                    if (!common.checkValue(option.objType)) {
                        result = data.ResponseList;
                        count = data.Count;
                    }
                    else if (option.objType == "json") {
                        result = data.ResponseJson.data;
                        count = data.ResponseJson.count;
                    }

                    $scope.names = result;
                    $scope.count = count;

                    var total = Math.floor(count / limit);

                    if (count % limit > 0)
                        total++;

                    $scope.pageCount = total;

                }).error(function (data, status, headers, config) {
                    common.alertMessage(data.Message, status);
                });

                $scope.onPageChange = function () {

                    option.pars.Start = $scope.currentPage;

                    $http.post(option.url, option.pars).success(function (data) {

                        var result;
                        if (!common.checkValue(option.objType))
                            result = data.ResponseList;
                        else if (option.objType == "json")
                            result = data.ResponseJson.data;

                        $scope.names = result;
                    }).error(function (data, status, headers, config) {
                        common.alertMessage(data.Message, status);
                    });

                };
            }
        });
    },

    formatDescForDate: function (date) {
        if (date < '1990-01-01')
            return "-";

        return date;
    },

    validateForm: function (form, style) {

        var isValid = true;
        if (!common.checkValue(form) || !common.checkValue(style)) {
            form = $("#formValidate");
            style = $(".help-block");
        }

        form.validator("validate");
        style.each(function () {

            var val = $(this)[0].textContent;
            if (common.checkValue(val)) {
                isValid = false;
            }
        });

        return isValid;
    },

    validator: function (form) {
        form.validate({
            onFocus: function () {
                this.parent().addClass('active');
                return false;
            },
            onBlur: function () {
                var $parent = this.parent();
                var _status = parseInt(this.attr('data-status'));
                $parent.removeClass('active');
                if (!_status) {
                    $parent.addClass('error');
                }
                return false;
            }
        });
    },

    checkValue: function (val) {
        if (val === "" || val === null || val === undefined)
            return false;

        return true;
    },

    checkBeforeLeave: function () {
        var currentUrl = ""
        var targetUrl = ""
        window.onbeforeunload = myOnBeforeUnload;

        function myOnBeforeUnload() {
            if (typeof this.href != "undefined") {
                currentUrl = this.href.toString().toLowerCase();
            } else {
                currentUrl = document.location.toString().toLowerCase();
            }

            //var flag = document.getElementById("MainContentPlaceHolder_MainContentPlaceHolder_tbFlag").value;

            if (currentUrl != targetUrl && targetUrl.length > 0 && targetUrl.indexOf("http://") > -1 && targetUrl.indexOf(".html") > -1) {
                currentUrl = "";
                targetUrl = "";
                return "未保存的活动将丢失，是否离开本页面";
            }
        }
        window.onload = function () {
            document.onclick = docOnClick;
        }
        function docOnClick(e) {
            if (event.srcElement.tagName == 'A') {
                targetUrl = event.srcElement.href.toString().toLowerCase();
            }
        }
    },

    ResetControls: function (parentControlID) {
        $('#' + parentControlID + '' + ' [clearafterclose=true]').each(function () {

            var obj = $(this);
            switch (obj[0].type) {
                case 'file':
                    obj.fileinput('clear');
                    break;
                case 'select-multiple':
                    obj.val("");
                    obj.trigger("chosen:updated");
                    break;
                default:
                    obj.val('');
                    break;
            }
        });
    },

    FormAjax: function (options) {
        var formData = new FormData($("#" + options.ID)[0]);
        common.loading(options.loadingCtrl);
        $.ajax({
            url: options.url,
            type: options.type,
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                if (common.checkValue(options.alert)) {
                    swal({
                        title: "",
                        text: "提交成功, 2秒后自动关闭",
                        type: "success",
                        timer: 2000,
                        showConfirmButton: true
                    },
                    function () {
                        swal.close();
                        options.sMethod(ctx);
                    });

                    return;
                }

                options.sMethod(ctx);
            },
            error: function (ctx) {

                common.loadComplete(options.loadingCtrl);

                if (options.fMethod === undefined || options.fMethod === null || options.fMethod === "") {

                    if (common.checkValue(ctx.responseJSON) && common.checkValue(ctx.responseJSON.Message))
                        common.alertMessage(ctx.responseJSON.Message, ctx.status);
                    else
                        common.alertMessage("操作失败,请重新提交", ctx.status);

                    return;
                }

                options.fMethod(ctx);
            }
        });
    },

    PutStorageSession: function (key, value) {
        if (typeof (Storage) !== "undefined") {
            sessionStorage[key] = value;
        }
        else {
            alert("抱歉，您的浏览器不支持 web 存储");
        }
    },

    GetStorageSession: function (key) {
        if (typeof (Storage) !== "undefined") {
            return sessionStorage[key];
        }
        else {
            alert("抱歉，您的浏览器不支持 web 存储");
        }
    },

    RemoveStorageSession: function (key) {
        if (typeof (Storage) !== "undefined") {
            sessionStorage.removeItem(key);
        }
        else {
            alert("抱歉，您的浏览器不支持 web 存储");
        }
    },

    GetUserType: function () {

        var user = common.GetStorageSession("user");

        if (!common.checkValue(user)) {
            window.location = "/login.html";
            return;
        }

        var obj = $.parseJSON(user);
        return obj.UserType;
    },

    GetUser: function () {

        var user = common.GetStorageSession("user");

        return user;
    },

    RemoveUser: function () {
        common.RemoveStorageSession("user");
    },

    GetUserLogo: function () {

        var user = common.GetStorageSession("user");

        if (!common.checkValue(user)) {
            window.location = "/login.html";
            return;
        }

        var obj = $.parseJSON(user);
        return obj.Logo;
    },

    ValidateFormJQ: function (formID, clickID, afterValidate) {
        //$("#" + formID).validate();
        $("#" + clickID).click(function () {
            //if ($("#" + formID).valid()) {
            if ($("#" + formID).validate('submitValidate')) {
                afterValidate();
            }

        });

    },

    CreateEditor: function (ctrlID) {

        var editor = new Simditor({
            textarea: $('#' + ctrlID + ''),
            toolbar: [
              'title',
                'bold',
                'italic',
                'underline',
                'strikethrough',
                'fontScale',
                'color',
                'ol',
                'ul',
                'blockquote',
                'code',
                'table',
                'link',
                'hr',
                'indent',
                'outdent',
                'alignment',
                'html'
            ]
        });

        return editor;

    }

}


